import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { CreateSubmissionRequest } from '@/types/submission';

async function handlePost(request: NextRequest): Promise<{ success: boolean; message: string }> {
  const body: CreateSubmissionRequest = await request.json();
  const { siteName, siteUrl, category, description, email, tags } = body;

  // 验证必填字段
  if (!siteName || !siteUrl || !category || !description || !email) {
    throw new Error('请填写所有必填字段');
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    throw new Error('请输入有效的邮箱地址');
  }

  // 验证URL格式
  try {
    new URL(siteUrl);
  } catch {
    throw new Error('请输入有效的网站地址');
  }

  // 检查是否已经提交过相同的网站
  const existingSubmission = await prisma.submission.findFirst({
    where: {
      siteUrl: siteUrl,
    },
  });

  if (existingSubmission) {
    throw new Error('该网站已经提交过，请勿重复提交');
  }

  // 创建提交记录
  await prisma.submission.create({
    data: {
      siteName,
      siteUrl,
      category,
      description,
      email,
      tags: tags || null,
      status: 0, // 待审核
    },
  });

  return {
    success: true,
    message: '提交成功！我们将在1-3个工作日内审核并回复',
  };
}

export const POST = withMiddleware(handlePost);